package middleware

import (
	"main/handlers"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// ProjectRequest 结构体表示通用的项目请求参数
type ProjectRequest struct {
	ProjectID          int    `json:"project_id"`                      // 项目 ID（可选，删除或更新时需要）
	ProjectName        string `json:"project_name" binding:"required"` // 项目名称（必填）
	ProjectCode        string `json:"project_code" binding:"required"` // 项目编码（必填）
	ProjectInstruction string `json:"project_instruction"`             // 项目介绍（可选）
}

// GetProjects 处理获取项目数据的请求
func GetProjects(c *gin.Context) {
	query := `
		SELECT * FROM project
		WHERE project_del != 1
	`

	results, err := handlers.ExecuteQuery(query)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch projects", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, results)
}

// PostProjects 处理新建项目的请求
func PostProjects(c *gin.Context) {
	var project ProjectRequest

	if err := c.ShouldBindJSON(&project); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	query := "INSERT INTO project (`project_name`, `project_code`, `project_instruction`) VALUES (?, ?, ?)"
	_, err := handlers.ExecuteNonQuery(query, project.ProjectName, project.ProjectCode, project.ProjectInstruction)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create project", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Project created successfully"})
}

// PutProjects 处理更新项目的请求
func PutProjects(c *gin.Context) {
	var project ProjectRequest

	if err := c.ShouldBindJSON(&project); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	if project.ProjectID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Project ID is required for updates"})
		return
	}

	query := `
		UPDATE project
		SET project_name = ?, project_code = ?, project_instruction = ?
		WHERE project_id = ?
	`
	_, err := handlers.ExecuteNonQuery(query, project.ProjectName, project.ProjectCode, project.ProjectInstruction, project.ProjectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update project", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Project updated successfully"})
}

// DeleteProjects 处理删除项目的请求
func DeleteProjects(c *gin.Context) {
	var projects []ProjectRequest

	if err := c.ShouldBindJSON(&projects); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	projectIDs := make([]interface{}, len(projects))
	placeholders := make([]string, len(projects))
	for i, project := range projects {
		if project.ProjectID == 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Project ID is required for deletion"})
			return
		}
		projectIDs[i] = project.ProjectID
		placeholders[i] = "?"
	}

	query := `
		UPDATE project
		SET project_del = 1
		WHERE project_id IN (` + strings.Join(placeholders, ",") + `)
	`

	_, err := handlers.ExecuteNonQuery(query, projectIDs...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete projects", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Projects deleted successfully"})
}
